package cn.otrue.patienthealthmanager.fragment;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.RosterListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Presence;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import cn.otrue.patienthealthmanager.R;
import cn.otrue.patienthealthmanager.activity.DoctorChatActivity;
import cn.otrue.patienthealthmanager.activity.MainActivity;
import cn.otrue.patienthealthmanager.adapter.DoctorCharlieAdpater;
import cn.otrue.patienthealthmanager.bean.DoctorBaseinfo;
import cn.otrue.patienthealthmanager.bean.HistoryChat;
import cn.otrue.patienthealthmanager.db.DBTools;
import cn.otrue.patienthealthmanager.utils.MyConst;
import cn.otrue.patienthealthmanager.xmpp.XmppTool;

import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.db.sqlite.SqlInfo;
import com.lidroid.xutils.db.sqlite.WhereBuilder;
import com.lidroid.xutils.db.table.DbModel;
import com.lidroid.xutils.exception.DbException;

/**
 * 找医生->聊天记录
 * 
 * @author G
 * 
 */
public class FindDoctorChatLogFragment extends BaseFragment implements
		OnTouchListener {

	private List<Map<String, String>> data = new ArrayList<Map<String, String>>();
	private ListView lv_doctor_char;

	private View rootView;
	private DoctorCharlieAdpater adpater;
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {

			Bundle bundle = msg.getData();
			String user = bundle.getString("user");
			String state = bundle.getString("state");
			for (int i = 0; i < data.size(); i++) {
				if (data.get(i).get("doctorUser").equals(user)) {
					data.get(i).put("state", state);
				}
			}
			adpater.notifyDataSetChanged();

		}
	};
	private List<DbModel> dbModle;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		rootView = inflater.inflate(R.layout.fragment_doctor_chat, container,
				false);

		initView(rootView);

		return rootView;
	}

	private void initFriendList() throws XMPPException, DbException {
		data.clear();
		List<HistoryChat> historyList = DBTools.db.findAll(Selector
				.from(HistoryChat.class));
		// List<DoctorBaseinfo> doctorList = DBTools.db
		// .findAll(DoctorBaseinfo.class);

		if (historyList != null && historyList.size() > 0) {

			String sql = "select * from (select * from "
					+ DBTools.getTableClass(DoctorBaseinfo.class)
					+ "  where mId='" + MyConst.getACCOUNT()
					+ "')  d join (select * from "
					+ DBTools.getTableClass(HistoryChat.class)
					+ "  where patientUser='" + MyConst.getACCOUNT()
					+ "') h on d.aliasAccount=h.doctorUser";

			dbModle = DBTools.db.findDbModelAll(new SqlInfo(sql));

			for (int i = 0; i < dbModle.size(); i++) {
				DbModel dbModel = dbModle.get(i);
				data.add(dbModel.getDataMap());
			}

			XMPPConnection connection = XmppTool.getConnection();
			// connection.login(arg0, arg1);
			Roster roster = connection.getRoster();

			Collection<RosterEntry> entries = roster.getEntries();
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			getRosterPresenceChange(roster);

			for (int i = 0; i < data.size(); i++) {

				for (RosterEntry entry : entries) {
					// if (entry.getType().equals(ItemType.both)) {
					// 获取好友在线状态
					Presence presence = roster.getPresence(entry.getUser());
					if (entry.getUser()
							.substring(0, entry.getUser().indexOf("@"))
							.equals(data.get(i).get("doctorUser"))
							&& presence.isAvailable()) {

						data.get(i).put("state", "0");
					} else {
						data.get(i).put("state", "1");
					}

				}

			}
			dbHandler.sendMessage(new Message());
		}

	}

	Handler dbHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			adpater = new DoctorCharlieAdpater(rootView.getContext(), data);

			lv_doctor_char.setAdapter(adpater);
		}

	};

	public void getRosterPresenceChange(final Roster roster) {

		if (roster != null) {
			roster.addRosterListener(new RosterListener() {
				// 有人添加好友时
				@Override
				public void entriesAdded(Collection<String> addresses) {

				}

				@Override
				public void entriesUpdated(Collection<String> addresses) {

				}

				@Override
				public void entriesDeleted(Collection<String> addresses) {

				}

				@Override
				public void presenceChanged(Presence prsnc) {
					Bundle bundle = new Bundle();

					String fromStr = prsnc.getFrom();
					String from = fromStr.substring(0, fromStr.lastIndexOf('/'));
					bundle.putString("user", from);
					if (prsnc.isAvailable()) {
						bundle.putString("state", "0");
					} else {
						bundle.putString("state", "1");
					}
					Message msg = new Message();
					msg.setData(bundle);
					handler.sendMessage(msg);

				}

			});
		}
	}

	private void initView(final View rootView) {

		lv_doctor_char = (ListView) rootView.findViewById(R.id.lv_doctor_char);
		lv_doctor_char.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {

				data.get(arg2).put("unreadNum", "0");
				adpater.notifyDataSetChanged();
				Intent intent = new Intent();

				intent.putExtra("from", data.get(arg2).get("jid"));

				intent.setClass(rootView.getContext(), DoctorChatActivity.class);
				try {

					HistoryChat historyChat = DBTools.db.findFirst(Selector
							.from(HistoryChat.class)
							.where("patientUser", "=", MyConst.getACCOUNT())
							.and(WhereBuilder.b("doctorUser", "=",
									data.get(arg2).get("doctorUser"))));
					if (historyChat != null) {
						historyChat.setUnreadNum(0);
						DBTools.db.update(historyChat);
					}
					((MainActivity) MyConst.activity).initNum();

				} catch (DbException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				startActivity(intent);

			}
		});

	}

	@Override
	public void onClick(View arg0) {

	}

	@Override
	public boolean onTouch(View arg0, MotionEvent arg1) {
		// TODO Auto-generated method stub
		return false;
	}

	public static Fragment newInstance() {
		return new FindDoctorChatLogFragment();
	}

	@Override
	public String setPageName() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		super.setUserVisibleHint(isVisibleToUser);
		if (isVisibleToUser) {
			MyConst.fragment = this;
			// 相当于Fragment的onResume
			changeList();
		} else {
			// 相当于Fragment的onPause
			MyConst.fragment = null;

		}
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		changeList();
	}

	public void changeList() {
		if (!TextUtils.isEmpty(MyConst.getACCOUNT())) {

			new Thread(new Runnable() {

				@Override
				public void run() {
					try {
						initFriendList();
					} catch (DbException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (XMPPException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}).start();

		}
	}

}
